import logging

from flask import current_app, jsonify
from flask import render_template
from flask import request
from flask import session

from info import redis_store
from info.models import User, News, Category
from info.modules.index import index_blu
from info.utils.response_code import RET


@index_blu.route("/news_list")
def news_list():
    """首页详情数据"""
    # 获取参数
    data = request.args
    cid = data.get("cid", "1")  # 分类id
    page = data.get("page", "1")  # 页数
    per_page = data.get("per_page", "10")  # 每页显示新闻条数
    # 校验参数
    try:
        cid = int(cid)
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    filters = [News.status == 0]
    if cid != 1:  # 表示当前数据不是最新数据
        # 需要添加条件
        filters.append(News.category_id == cid)
    # 查询数据
    try:
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page, per_page, False)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="数据查询错误")
    # 取到当前页面的数据
    news_model_list = paginate.items  # 获取模型对象
    total_page = paginate.pages
    current_page = paginate.page
    # 将模型对象列表转成字典列表
    news_dict_li = []
    for news in news_model_list:
        news_dict_li.append(news.to_basic_dict())
    data = {
        "total_page": total_page,
        "current_page": current_page,
        "news_dict_li": news_dict_li
    }
    # 返回数据
    return jsonify(errno=RET.OK, errmsg="OK", data=data)


@index_blu.route("/")
def index():
    # session["name"] = "laowang"
    # redis_store.set("name", "888")
    # 显示用户是否登陆的逻辑
    # 获取当前用户id
    user_id = session.get("user_id", None)
    user = None
    if user_id:
        try:
            # 查询用户模型
            user = User().query.get(user_id)
        except Exception as e:
            current_app.logger.error(e)

    # 显示右侧新闻排行
    news_list = []
    try:
        news_list = News.query.order_by(News.clicks.desc()).limit(10)
        # print(news_list)
        # print(type(news_list))
    except Exception as e:
        current_app.logger.error(e)
    # 定义一个空列表，里面装的是字典
    news_dict_li = []
    # 遍历对象列表，将对象的字典添加到字典列表中
    for news in news_list:
        news_dict_li.append(news.to_basic_dict())

    # 获取新闻分类，并默认设置第1个分类选中
    # 1获取新闻分类
    categories = Category.query.all()
    # 2定义列表保存分类数据
    category_li = []
    for category in categories:
        category_li.append(category.to_dict())

    data = {"user": user.to_dict() if user else None,
            "news_dict_li": news_dict_li,
            "category_li": category_li}
    # print(news_dict_li)
    logging.debug("测试调试值")
    return render_template('news/index.html', data=data)


@index_blu.route('/favicon.ico')
def favicon():
    return current_app.send_static_file("new/favicon.ico")